//
//  YBMsgC2CListVC.m
//  YBHiMo
//
//  Created by YB007 on 2021/8/20.
//  Copyright © 2021 YB007. All rights reserved.
//

#import "YBMsgC2CListVC.h"
#import "TConversationCell.h"
#import "THeader.h"
#import "TUIKit.h"
#import "TChatC2CController.h"
#import "MessageHeaderV.h"

#import "MessageListCell.h"
#import "MessageListModel.h"
#import "JCHATConversationViewController.h"
#import "MessageFansVC.h"
#import "MsgTopPubVC.h"
#import "SelPeopleV.h"
#import "JCHATAlertViewWait.h"
#import "MsgSysVC.h"

#import "OrderMessageVC.h"

@interface YBMsgC2CListVC ()<UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource, UIPopoverPresentationControllerDelegate,V2TIMConversationListener>{
    dispatch_group_t _imgListGroup;
    SelPeopleV * _selV;
    
    TConversationCellData *conver_admin1;//官方通知
    TConversationCellData *conver_admin2;//系统通知
    TConversationCellData *_conversation_fans;       //顶部-粉丝
    TConversationCellData *_conversation_zan;        //顶部-赞
    TConversationCellData *_conversation_at;         //顶部-@
    TConversationCellData *_conversation_comment;    //顶部-评论
    
    TConversationCellData *_conversation_ctr;        //风控管理员
    TConversationCellData *_conversation_goodsorder;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *data;
@property(nonatomic,strong)MessageHeaderV *headerV;

@end

@implementation YBMsgC2CListVC
#pragma mark --消息监听
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
    [self updateConversations];
}

-(void)clearUnreadNum {
    for (int i = 0; i < _data.count; i ++) {
        TConversationCellData *data = _data[i];
        data.unRead = 0;
        NSMutableArray *new_a = [NSMutableArray arrayWithArray:_data];
        [new_a replaceObjectAtIndex:i withObject:data];
        _data = [NSArray arrayWithArray:new_a];
    }
    [_tableView reloadData];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

    
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[PublicObj publicInstance]addCusDelayedRemove];
    [self updateConversations];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGB(245, 245, 245);
    self.subNavi.backgroundColor= UIColor.whiteColor;
    
    _data = [NSArray array];
    
    _imgListGroup = dispatch_group_create();
    
    _sysDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"sysnotice"];
    
    
    self.titleL.text = YZMsg(@"消息");
    self.titleL.textColor= UIColor.blackColor;
    self.leftBtn.hidden = NO;
    [self.leftBtn setImage:[UIImage imageNamed:@"msg_linkman"] forState:0];
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"全部已读") forState:0];
    [self.rightBtn setTitleColor:[UIColor blackColor] forState:0];
    self.rightBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
    
    _headerV = [[[NSBundle mainBundle]loadNibNamed:@"MessageHeaderV" owner:nil options:nil]objectAtIndex:0];
    
    float botSpace = _isPush?0:tabBarHeight;
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-naviHight-botSpace)];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.backgroundColor = RGB(245, 245, 245);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = 0;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    [self addNoti];
}
- (void)clickNaviLeftBtn {
    [self selPeopleFun];
}
- (void)clickNaviRightBtn {
    
    int unread = 0;
    for (TConversationCellData *conversation in _data){
        unread += conversation.unRead;
        [[YBImManager shareInstance] clearUnreadConvId:conversation.convId sendNot:NO];
    }
    unread += [_conversation_fans unRead];
    unread += [_conversation_zan unRead];
    unread += [_conversation_at unRead];
    unread += [_conversation_comment unRead];
    unread += [_conversation_ctr unRead];
    [[YBImManager shareInstance] clearUnreadConvId:_conversation_fans.convId sendNot:NO];
    [[YBImManager shareInstance] clearUnreadConvId:_conversation_zan.convId sendNot:NO];
    [[YBImManager shareInstance] clearUnreadConvId:_conversation_at.convId sendNot:NO];
    [[YBImManager shareInstance] clearUnreadConvId:_conversation_comment.convId sendNot:NO];
    [_headerV clearRedPoint];
    if (unread == 0) {
        [MBProgressHUD showPop:YZMsg(@"当前暂无未读消息")];
    }else {
        [MBProgressHUD showPop:YZMsg(@"已经忽略未读消息")];
        [PublicObj setTabbarBadgeValue:0];
        [self updateConversations];
    }
   
}
-(void)addNoti {
    [[V2TIMManager sharedInstance] addConversationListener:self];

//    [self removeNoti];
//    NSNotificationCenter *notCenter = [NSNotificationCenter defaultCenter];
//    [notCenter addObserver:self selector:@selector(onRefreshConversations:) name:TUIKitNotification_TIMRefreshListener object:nil];
}

-(void)removeNoti {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc {
    [self removeNoti];
}
- (void)onRefreshConversations:(NSNotification *)notification {
    //NSLog(@"xxxxxxokokokokokoko");
    [self updateConversations];
}

- (void)updateConversations{
    YBWeakSelf;
     _data = [NSMutableArray array];
    [[YBImManager shareInstance]getAllConversationList:^(NSMutableArray *CovList, BOOL isSuccess) {
            if(isSuccess){
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf goReload:CovList];
                });
            }
    }];

//    YBWeakSelf;
//    [[YBImManager shareInstance] getLastDisplayStringWith:_imgListGroup finish:^(NSArray *transformArray) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf goReload:transformArray];
//        });
//    }];
}
-(void)goReload:(NSArray *)reloadA {
    /*
    NSMutableDictionary *sortDic = [NSMutableDictionary dictionary];
    for (TConversationCellData *cellData in reloadA) {
        if (cellData && cellData.timestamp) {
            NSLog(@"xxxx-chat-have:%@==uid:%@",cellData.timestamp,cellData.convId);
            [sortDic setObject:cellData forKey:cellData.timestamp];
        }else{
            NSLog(@"xxxx-chat-not:%@",cellData);
        }
    }
    NSArray *sortAllKey = [sortDic allKeys];
    NSArray *sortResult = [sortAllKey sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
        return [obj2 compare:obj1];
    }];
    */
    NSSortDescriptor * sortDes = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    NSArray *sortResult = [reloadA sortedArrayUsingDescriptors:@[sortDes]];
    NSMutableArray *m_group_array = [NSMutableArray array];
    NSMutableArray *m_c2c_array = [NSMutableArray array];
    for (TConversationCellData *sortData in sortResult) {
        //TConversationCellData *sortData = (TConversationCellData*)[sortDic objectForKey:key];
        //NSLog(@"xxxx-chat-have:%@==uid:%@",sortData.timestamp,sortData.convId);
        if(sortData.convType == TConv_Type_Group){
            [m_group_array addObject:sortData];
        }else if (sortData.convType == TConv_Type_C2C){
            NSString *imName = sortData.convId;
            if ([imName isEqual:@"dsp_admin_1"]) {
                // 因为总要admi1在第一位这里暂时不加入,for循环结束再插入
                //[m_c2c_array insertObject:sortData atIndex:0];
                conver_admin1 = sortData;
            }else if ([imName isEqual:@"dsp_admin_2"]){
                // 因为总要admi2在第二位这里暂时不加入,for循环结束再插入
                //[m_c2c_array insertObject:sortData atIndex:1];
                conver_admin2 = sortData;
            }else if ([imName isEqual:@"dsp_fans"]) {
                //粉丝
                _conversation_fans = sortData;
            }else if ([imName isEqual:@"dsp_like"]){
                //赞
                _conversation_zan = sortData;
            }else if ([imName isEqual:@"dsp_at"]){
                //@
                _conversation_at = sortData;
            }else if ([imName isEqual:@"dsp_comment"]){
                //评论
                _conversation_comment = sortData;
            }else if ([imName isEqual:@"dsp_admin_control"]){
                //风控管理员
                _conversation_ctr = sortData;
            }else if([imName containsString:@"dsp_user_"]){
                // dsp_user_live 【用于推送】
                
            }else if ([imName isEqual:@"goodsorder_admin"]){
                //订单管理员【未要求具体排序这里add即可】
                _conversation_goodsorder = sortData;
                [m_c2c_array addObject:sortData];
            }else{
                [m_c2c_array addObject:sortData];
            }
        }
    }
    // 检查dsp_admin_1、dsp_admin_2是否缺失
    if (!conver_admin2) {
        conver_admin2 = [[YBImManager shareInstance] createEmptyCellDataWithId:@"dsp_admin_2"];
    }
    if (!conver_admin1) {
        conver_admin1 = [[YBImManager shareInstance] createEmptyCellDataWithId:@"dsp_admin_1"];
    }
    if (_conversation_ctr) {
        conver_admin2.unRead += _conversation_ctr.unRead;
    }
    [m_c2c_array insertObject:conver_admin2 atIndex:0];
    [m_c2c_array insertObject:conver_admin1 atIndex:0];
    // 刷新顶部
    [self reloadTopUnread];
    
    [self requestUserMessage:[m_c2c_array mutableCopy]];
}

- (void)requestUserMessage:(NSArray *)msgArray{
    NSString *uids = @"";
    for (TConversationCellData *data in msgArray) {
        uids = [uids stringByAppendingFormat:@"%@,",data.convId];
    }
    if (uids.length > 0) {
        //去掉最后一个逗号
        uids = [uids substringToIndex:[uids length] - 1];
    }
    NSMutableArray *m_array = [NSMutableArray array];
    [WYNetworking postWithUrl:[NSString stringWithFormat:@"User.getMultiInfo&uids=%@",uids] Dic:@{} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            for (int i = 0; i < [info count]; i ++) {
                NSDictionary *plantSubDic = info[i];
                for (TConversationCellData *data in msgArray) {
                    if ([data.convId isEqual:strFormat([plantSubDic valueForKey:@"id"])]) {
                        [data updateUserInfo:plantSubDic];
                        [m_array addObject:data];
                    }
                }
            }
            _data = [NSArray arrayWithArray:m_array];
            [_tableView reloadData];
        }
    } Fail:^(id fail) {
        
    }];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [TConversationCell getSize].height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return _window_width/4+5;
    }
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        //_headerV = [[[NSBundle mainBundle]loadNibNamed:@"MessageHeaderV" owner:nil options:nil]objectAtIndex:0];
        _headerV.frame = CGRectMake(0, 0, _window_width, _window_width/4+5);
        _headerV.backgroundColor = UIColor.whiteColor;
        _headerV.headerBgV.backgroundColor = UIColor.whiteColor;
        _headerV.fansBtn = [PublicObj setUpImgDownText:_headerV.fansBtn space:15];
        _headerV.zanBtn = [PublicObj setUpImgDownText:_headerV.zanBtn space:15];
        _headerV.aiTeBtn = [PublicObj setUpImgDownText:_headerV.aiTeBtn space:15];
        _headerV.commentBtn = [PublicObj setUpImgDownText:_headerV.commentBtn space:15];
        YBWeakSelf;
        _headerV.msgEvent = ^(NSString *type) {
            [weakSelf msgClickEvent:type];
        };
        return _headerV;
    }
    return nil;
}
-(void)msgClickEvent:(NSString *)type {
    //rk_顶部红点
    if ([type isEqual:@"粉丝"]) {//=====>不需要翻译
        [[YBImManager shareInstance]clearUnreadConvId:_conversation_fans.convId sendNot:YES];
        _headerV.fansPoint.hidden = YES;
    }else if ([type isEqual:@"赞"]){
        [[YBImManager shareInstance]clearUnreadConvId:_conversation_zan.convId sendNot:YES];
        _headerV.zanPoint.hidden = YES;
    }else if ([type isEqual:@"@我的"]){
        [[YBImManager shareInstance]clearUnreadConvId:_conversation_at.convId sendNot:YES];
        _headerV.atPoint.hidden = YES;
    }else if ([type isEqual:@"评论"]){
        [[YBImManager shareInstance]clearUnreadConvId:_conversation_comment.convId sendNot:YES];
        _headerV.comPoint.hidden = YES;
    }
    if ([type isEqual:@"粉丝"]) {
        MessageFansVC *fansVC = [[MessageFansVC alloc]init];
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:fansVC animated:YES];
        NSLog(@"==粉丝==");
    }else {
        //赞、@我的、评论
        MsgTopPubVC *pubVC = [[MsgTopPubVC alloc]init];
        pubVC.type = type;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:pubVC animated:YES];
         NSLog(@"==赞==@我的==评论==");
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row>1) {
        return YES;
    }
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YZMsg(@"删除");
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    TConversationCellData *conv = _data[indexPath.row];
    NSMutableArray *new_a = [NSMutableArray arrayWithArray:_data];
    [new_a removeObjectAtIndex:indexPath.row];
    _data = [NSArray arrayWithArray:new_a];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
   
    [[YBImManager shareInstance]clearUnreadConvId:conv.convId sendNot:YES];
    NSString *userid = [NSString stringWithFormat:@"c2c_%@",conv.convId];

    [[V2TIMManager sharedInstance] deleteConversation:userid succ:^{
        NSLog(@"success");
    } fail:^(int code, NSString *desc) {
        NSLog(@"failure, code:%d, desc:%@", code, desc);
    }];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [[NSNotificationCenter defaultCenter] postNotificationName:TUIKitNotification_TIMCancelunread object:nil];
//    });

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

    TConversationCellData *conversation = [_data objectAtIndex:indexPath.row];
    [[YBImManager shareInstance] clearUnreadConvId:conversation.convId sendNot:YES];
    
    if ([conversation.convId isEqual:@"dsp_admin_1"]||[conversation.convId isEqual:@"dsp_admin_2"]) {
        if ([conversation.convId isEqual:@"dsp_admin_2"]) {
            [[YBImManager shareInstance] clearUnreadConvId:_conversation_ctr.convId sendNot:NO];
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSString *dataStr = [dateFormatter stringFromDate:currentDate];
            [[NSUserDefaults standardUserDefaults]setObject:dataStr forKey:@"sys_time_2"];

        }else{
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
            NSString *dataStr = [dateFormatter stringFromDate:currentDate];
            [[NSUserDefaults standardUserDefaults]setObject:dataStr forKey:@"sys_time_1"];

        }
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:conversation.userHeader forKey:@"avatar"];
        [dic setObject:conversation.convId forKey:@"id"];
        [dic setObject:conversation.userName forKey:@"user_nickname"];
        //[dic setObject:conversation.lastConv forKey:@"conversation"];
        
        
        MessageListModel *model = [MessageListModel modelWithDictionary:dic];
        MsgSysVC *sysVC = [[MsgSysVC alloc]init];
        sysVC.isWhiteStyle = YES;
        sysVC.listModel = model;
        sysVC.uiFrom = UiFrom_Default;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:sysVC animated:YES];
    }else if([conversation.convId isEqual:@"goodsorder_admin"]){
        OrderMessageVC *order = [[OrderMessageVC alloc]init];
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:order animated:YES];
    }else{
        TChatC2CController *chat = [[TChatC2CController alloc] init];
        chat.conversation = _data[indexPath.row];
        [[YBBaseAppDelegate sharedAppDelegate] pushViewController:chat animated:YES];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TConversationCell *cell  = [tableView dequeueReusableCellWithIdentifier:TConversationCell_ReuseId];
    if(!cell){
        cell = [[TConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TConversationCell_ReuseId];
    }
    TConversationCellData *celldata =[_data objectAtIndex:indexPath.row];
    [cell setData:celldata];
    return cell;
}

- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

-(void)selPeopleFun {
    YBWeakSelf;
    if (!_selV) {
        _selV = [[SelPeopleV alloc]initWithFrame:CGRectMake(0, _window_height, _window_width, _window_height) showType:@"1" selUser:^(NSString *state, MessageListModel *userModel) {
            [weakSelf selCallBack:state uModel:userModel];
        }];
        [self.view addSubview:_selV];
    }
    [UIView animateWithDuration:0.3 animations:^{
        _selV.frame = CGRectMake(0, 0, _window_width, _window_height);
        self.tabBarController.tabBar.hidden = YES;
    }];
}

-(void)selCallBack:(NSString *)state uModel:(MessageListModel *)model{
   
    if ([state isEqual:@"关闭"]) {
        [UIView animateWithDuration:0.3 animations:^{
            _selV.frame = CGRectMake(0, _window_height, _window_width, _window_height);
        } completion:^(BOOL finished) {
            self.tabBarController.tabBar.hidden = NO;
            [_selV removeFromSuperview];
            _selV = nil;
        }];
    }else {
        //单聊
        [UIView animateWithDuration:0.3 animations:^{
            _selV.frame = CGRectMake(0, _window_height, _window_width, _window_height);
        } completion:^(BOOL finished) {
            self.tabBarController.tabBar.hidden = NO;
            [_selV removeFromSuperview];
            _selV = nil;
            //去单聊页面
            NSLog(@"===去单聊页面===%@",model.uidStr);
            NSDictionary *userDic = @{
                @"id":model.uidStr,
                @"user_nickname":model.unameStr,
                @"avatar":model.iconStr,
            };
            [[YBMessageManager shareManager] chatWithUser:userDic];
        }];
        
    }
   
}

#pragma mark - 刷新顶部未读状态
-(void)reloadTopUnread {
    if (_conversation_fans.unRead > 0) {
        _headerV.fansPoint.hidden = NO;
        _headerV.fansPoint.text = [NSString stringWithFormat:@"%d",_conversation_fans.unRead];
        //个位数显示圆点，两位及以上显示椭圆
        if (_conversation_fans.unRead < 10) {
            _headerV.fanPointWidth.constant = _headerV.fansPoint.frame.size.height;
        }else{
            _headerV.fanPointWidth.constant = _headerV.fansPoint.frame.size.height+8;
        }
    }
    if (_conversation_zan.unRead > 0) {
        _headerV.zanPoint.hidden = NO;
        _headerV.zanPoint.text = [NSString stringWithFormat:@"%d",_conversation_zan.unRead];
        //个位数显示圆点，两位及以上显示椭圆
        if (_conversation_zan.unRead < 10) {
            _headerV.zanPointWidth.constant = _headerV.zanPoint.frame.size.height;
        }else{
            _headerV.zanPointWidth.constant = _headerV.zanPoint.frame.size.height+8;
        }
    }
    if (_conversation_at.unRead > 0) {
        _headerV.atPoint.hidden = NO;
        _headerV.atPoint.text = [NSString stringWithFormat:@"%d",_conversation_at.unRead];
        //个位数显示圆点，两位及以上显示椭圆
        if (_conversation_at.unRead < 10) {
            _headerV.atPointWidth.constant = _headerV.atPoint.frame.size.height;
        }else{
            _headerV.atPointWidth.constant = _headerV.atPoint.frame.size.height+8;
        }
    }
    if (_conversation_comment.unRead > 0) {
        _headerV.comPoint.hidden = NO;
        _headerV.comPoint.text = [NSString stringWithFormat:@"%d",_conversation_comment.unRead];
        //个位数显示圆点，两位及以上显示椭圆
        if (_conversation_comment.unRead < 10) {
            _headerV.comPointWidth.constant = _headerV.comPoint.frame.size.height;
        }else{
            _headerV.comPointWidth.constant = _headerV.comPoint.frame.size.height+8;
        }
    }
}
@end

